//
//  TXPFragmentViewController.m
//  StayAwhile
//
//  Created by dllo on 16/1/27.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "TXPFragmentViewController.h"
#import "TXPFragmentModel.h"
#import "TXPTableViewCell_Image.h"
#import "TXPTableViewCell_word.h"
#import "TXPCacheFile.h"
#import "TXPFragmentDetailPageViewController.h"
#import <MJRefresh.h>
@interface TXPFragmentViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) NSMutableArray *allArray;
@property (nonatomic, retain) UITableView *fragmentTableView;
@property (nonatomic, assign) CGFloat cellHeight;
@property(nonatomic,assign)NSInteger start;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉
@property (nonatomic, assign) int flag; //记录当前翻到了第几页
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, copy) NSString *time;

@end

@implementation TXPFragmentViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.allArray = [NSMutableArray array];
    
    self.view.backgroundColor =[UIColor yellowColor];
    
    self.fragmentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 69) style:UITableViewStylePlain];
    self.fragmentTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.fragmentTableView];
    self.fragmentTableView.dataSource = self;
    self.fragmentTableView.delegate = self;
    
    [self.fragmentTableView registerClass:[TXPTableViewCell_Image class]  forCellReuseIdentifier:@"coverimgCell"];
    [self.fragmentTableView registerClass:[TXPTableViewCell_word class] forCellReuseIdentifier:@"wordCell"];
    
    
    self.filePath = [TXPCacheFile createFilePathFromDocumentWithFolders:@[@"HomePage", @"FragmentPage"] fileName:@"FragmentPage.txt"];
    NSLog(@"filePath = %@", self.filePath);
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath]) {
        NSData *data = [NSData dataWithContentsOfFile:self.filePath];
        NSMutableDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *dataDic = [bigDic objectForKey:@"data"];
        NSMutableArray *listArray = [dataDic objectForKey:@"list"];
        for (NSMutableDictionary *dic in listArray) {
            TXPFragmentModel *fragmentModel = [[TXPFragmentModel alloc] init];
            [fragmentModel setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:fragmentModel];
        }
    }
    
    
    // 下拉刷新
    self.isUpLoading = NO;
//    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(addHeader)];
//    [header beginRefreshing];
//    self.fragmentTableView.mj_header = header;
    self.fragmentTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self addHeader];
        
    }];
    [self.fragmentTableView.mj_header beginRefreshing];
    
    self.fragmentTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self addFooter];
        
    }];
//    self.fragmentTableView.mj_footer.automaticallyHidden = NO;
    
    
    
    // 解析碎片页面数据
    
}

- (void)addHeader{
    self.start = 0;
    self.isUpLoading = NO;
    [self GetData];
}


- (void)GetData{
    
    
    [TXPAFNetworkingBlock PostAFNURLWithString:@"http://api2.pianke.me/timeline/list" Body:@{@"start ":@"0", @"client":@"2", @"auth":@"D5JqESWyo65DCsV8HMPqm1TJxQJDm2ZrSIpDtkUWNm1cWP229FNSBxa7fw", @"limit":@"10"} Cookie:nil resultBlock:^(id result) {
//        NSLog(@"%@", result);
//        NSLog(@"%ld", (long)str);
        if (self.isUpLoading == NO) {
            [self.allArray removeAllObjects];
        }
        NSMutableDictionary *dataDic = [result objectForKey:@"data"];
        NSMutableArray *listArray = [dataDic objectForKey:@"list"];
        
        for (NSMutableDictionary *dic in listArray) {
            TXPFragmentModel *fragmentModel = [[TXPFragmentModel alloc] init];
            [fragmentModel setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:fragmentModel];
        }
        [self.fragmentTableView reloadData];
        
        TXPFragmentModel *fragmentmodel = [self.allArray lastObject];
        self.time = fragmentmodel.addtime;
        NSData *data = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
        [TXPCacheFile saveDataOnLocal:data localPath:self.filePath];
        [self.fragmentTableView.mj_header endRefreshing];
//        [self.fragmentTableView.mj_footer endRefreshing];

    } errorBlock:^(NSError *error) {
        NSLog(@"error===%@", error);
        
    }];

    
}
- (void)addFooter{
    self.start+= 10;
    self.isUpLoading = YES;
    [self GetFooterData:self.start Time:self.time];
}

- (void)GetFooterData:(NSInteger)str Time:(NSString *)time{
    [TXPAFNetworkingBlock PostAFNURLWithString:@"http://api2.pianke.me/timeline/list" Body:@{@"start ": [NSString stringWithFormat:@"%ld", (long)str], @"client":@"2",@"addtime":self.time, @"auth":@"D5JqESWyo65DCsV8HMPqm1TJxQJDm2ZrSIpDtkUWNm1cWP229FNSBxa7fw", @"limit":@"10"} Cookie:nil resultBlock:^(id result) {
        NSLog(@"%@", result);
        NSMutableDictionary *dataDic = [result objectForKey:@"data"];
        NSMutableArray *listArray = [dataDic objectForKey:@"list"];
        
        for (NSMutableDictionary *dic in listArray) {
            TXPFragmentModel *fragmentModel = [[TXPFragmentModel alloc] init];
            [fragmentModel setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:fragmentModel];
        }
        [self.fragmentTableView reloadData];

        TXPFragmentModel *fragmentmodel = [self.allArray lastObject];
        self.time = fragmentmodel.addtime;
        NSData *data = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
        [TXPCacheFile saveDataOnLocal:data localPath:self.filePath];
//        [self.fragmentTableView.mj_header endRefreshing];
        [self.fragmentTableView.mj_footer endRefreshing];

    } errorBlock:^(NSError *error) {
        
        
    }];
    

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TXPFragmentModel *fragmentModel = [[TXPFragmentModel alloc] init];
    fragmentModel = [self.allArray objectAtIndex:indexPath.row];
    if (![fragmentModel.coverimg isEqualToString:@""] && [fragmentModel.songid isEqualToString:@""]) {
        TXPTableViewCell_Image *image_cell = [tableView dequeueReusableCellWithIdentifier:@"coverimgCell"];
        image_cell.selectionStyle = UITableViewCellSelectionStyleNone;
        image_cell.fraModel = fragmentModel;
        self.cellHeight = image_cell.contentHeight;
        return image_cell;
    }
    if ([fragmentModel.coverimg isEqualToString:@""] && [fragmentModel.songid isEqualToString:@""]) {
        TXPTableViewCell_word *word_cell = [tableView dequeueReusableCellWithIdentifier:@"wordCell"];
        word_cell.selectionStyle = UITableViewCellSelectionStyleNone;
        word_cell.fraModel = fragmentModel;
        self.cellHeight = word_cell.labelHeight;
        
        return word_cell;
        
    }
    if (![fragmentModel.songid isEqualToString:@""] && ![fragmentModel.coverimg isEqualToString:@""]) {
        TXPTableViewCell_Image *image_cell = [tableView dequeueReusableCellWithIdentifier:@"coverimgCell"];
        image_cell.selectionStyle = UITableViewCellSelectionStyleNone;
        image_cell.fraModel = fragmentModel;
        self.cellHeight = image_cell.contentHeight;
        return image_cell;

        return image_cell;
    }
    
    TXPTableViewCell_word *word_cell = [tableView dequeueReusableCellWithIdentifier:@"wordCell"];
    word_cell.selectionStyle = UITableViewCellSelectionStyleNone;
    word_cell.fraModel = fragmentModel;
    self.cellHeight = word_cell.labelHeight;
    
    return word_cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    TXPFragmentModel *fragmentModel = [[TXPFragmentModel alloc] init];
    fragmentModel = [self.allArray objectAtIndex:indexPath.row];
    if (![fragmentModel.coverimg isEqualToString:@""] && [fragmentModel.songid isEqualToString:@""]) {
        return self.cellHeight;
    }
    if ([fragmentModel.coverimg isEqualToString:@""] && [fragmentModel.songid isEqualToString:@""]) {
        
        return self.cellHeight;
        
    }
    if (![fragmentModel.songid isEqualToString:@""] && ![fragmentModel.coverimg isEqualToString:@""]) {
        return self.cellHeight;
    }
    
    return self.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TXPFragmentModel *fragmentModel = [[TXPFragmentModel alloc] init];
    fragmentModel = [self.allArray objectAtIndex:indexPath.row];
    
    TXPFragmentDetailPageViewController *fragmentDetailPageVC = [[TXPFragmentDetailPageViewController alloc] init];
    fragmentDetailPageVC.fragmentmodel = fragmentModel;
    [self.navigationController pushViewController:fragmentDetailPageVC animated:YES];
  
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
